<template>
  <button 
    class="copy-btn" 
    @click="copyContent" 
    :title="title"
    :class="{ 'copy-success': copied }"
  >
    <i class="bi" :class="[copied ? 'bi-check-lg' : 'bi-clipboard']"></i>
    <span class="copy-tooltip">{{ copied ? '已复制' : title }}</span>
  </button>
</template>

<script>
export default {
  name: 'CopyButton',
  props: {
    // 要复制的内容
    content: {
      type: String,
      required: true
    },
    // 复制按钮的标题提示
    title: {
      type: String,
      default: '复制'
    }
  },
  data() {
    return {
      copied: false,
      resetTimeout: null
    };
  },
  methods: {
    async copyContent() {
      try {
        // 使用 Clipboard API 复制内容
        await navigator.clipboard.writeText(this.content);
        
        // 更新状态为已复制，显示成功图标
        this.copied = true;
        
        // 清除之前的定时器（如果存在）
        if (this.resetTimeout) {
          clearTimeout(this.resetTimeout);
        }
        
        // 2秒后重置图标
        this.resetTimeout = setTimeout(() => {
          this.copied = false;
        }, 2000);
        
      } catch (err) {
        console.error('复制失败:', err);
        // 如果应用中有通知组件，可以在这里显示错误通知
      }
    }
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.resetTimeout) {
      clearTimeout(this.resetTimeout);
    }
  }
};
</script>

<style scoped>
.copy-btn {
  background: transparent;
  border: none;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s ease;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  opacity: 0.7;
  font-size: 1rem;
  position: relative;
}

.copy-btn:hover {
  opacity: 1;
  background-color: rgba(0, 0, 0, 0.1);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.copy-btn i {
  font-size: 1.1rem;
}

.copy-btn.copy-success {
  color: #28a745;
  opacity: 1;
}

.copy-tooltip {
  position: absolute;
  bottom: -25px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.75rem;
  white-space: nowrap;
  opacity: 0;
  visibility: hidden;
  transition: all 0.2s ease;
  z-index: 10;
}

.copy-btn:hover .copy-tooltip {
  opacity: 1;
  visibility: visible;
}
</style>